package edu.kit.aifb.ldsbench.cli.util2;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import edu.kit.aifb.ldstream.env.Environment;
import edu.kit.aifb.ldstream.learner.out.xml.Tags;
import edu.kit.aifb.ldstream.learner.tasks.mod.ModStatistics;
import edu.kit.aifb.ldstream.stat.distrib.IDistribution;

public class ModStatsXMLReader {

	private File file;
	private DocumentBuilder builder;

	public ModStatsXMLReader(String filePath){
		File file = new File(filePath);
		if(!file.exists()){
			throw new IllegalArgumentException(Environment.SIMPLE_STATS_RESULT_FILE_NAME + " not found");
		}
		this.file = file;
		try {
			this.builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}
	}

	public ModStatistics read(){
		ModStatistics stats = new ModStatistics();

		Document doc;
		try {
			doc = this.builder.parse(this.file);
			Element root = doc.getDocumentElement();

			double coherence =  getDoubleValueText(root.getElementsByTagName(Tags.COHERENCE_TAG));
			stats.setStructuredness(coherence);

			double linkage = getDoubleValueText(root.getElementsByTagName(Tags.LINKAGE_TAG));
			stats.setLinkageDegree(linkage);

			int numTriples = getIntValueText(root.getElementsByTagName(Tags.NUM_TRIPLES_TAG));
			stats.setNumTriples(numTriples);
 
			int numTypes = getIntValueText(root.getElementsByTagName(Tags.NUM_TYPES_TAG));
			stats.setNumTypes(numTypes);

			int numInstance = getIntValueText(root.getElementsByTagName(Tags.NUM_INSTANCES));
			stats.setNumInstances(numInstance);
			
			int numEvents = getIntValueText(root.getElementsByTagName(Tags.NUM_EVENTS));
			stats.setNumEvents(numEvents);

			IDistribution bandwidth = DistributionXMLReader.readDistribution(
					root.getElementsByTagName(Tags.BANDWIDTH_DISTRIBUTION_TAG).item(0));
			stats.setBandwidthDistribution(bandwidth);

			IDistribution jitter = DistributionXMLReader.readDistribution(
					root.getElementsByTagName(Tags.JITTER_DISTRIBUTION_TAG).item(0));
			stats.setJitterDistribution(jitter);

		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return stats;
	}


	private double getDoubleValueText(NodeList n){
		return Double.parseDouble(n.item(0).getTextContent());
	}

	private int getIntValueText(NodeList n){
		return Integer.parseInt(n.item(0).getTextContent());
	}
}
